/*
  底部导航
  如果想要保持状态，可以使用 IndexStack
  AutomaticKeepAliveClientMixin 只对TabBar有用
 */

import 'package:flutter/material.dart';
import 'package:flutter_app/1_base/18_register.dart';
import 'package:flutter_app/1_base/18_search.dart';
import 'package:flutter_app/1_base/18_tab_game.dart';
import 'package:flutter_app/1_base/18_tab_shop.dart';

import '18_login.dart';
import '18_tab_person.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  final routers = {
    '/login': (BuildContext context) => Login(),
    '/search': (BuildContext context) => Search(),
    '/register': (BuildContext context) => Register(),
  };

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      routes: {
        '/': (BuildContext context) => NavigationBar(),
      },
      onGenerateRoute: (RouteSettings settings) {
        return MaterialPageRoute(builder: routers[settings.name] as Widget Function(BuildContext));
      },
    );
  }
}

class NavigationBar extends StatefulWidget {

  final int index;

  NavigationBar({Key? key, this.index=0}): super(key: key);

  _NavigationBarState createState() => _NavigationBarState(index);

}

class _NavigationBarState extends State<NavigationBar> {

  int _currentIndex = 0;

  _NavigationBarState(index) {
    this._currentIndex = index;
  }

  List<Widget> _pageList = [
    GamePage(),
    ShopPage(),
    PersonPage()
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('底部导航'),
      ),
      // 保持状态，不刷新
      body: IndexedStack(
        index: _currentIndex,
        children: _pageList,
      ),
      bottomNavigationBar: BottomNavigationBar(
        // 将选中和未选中设置成相同大小即可
        selectedFontSize: 12,
        backgroundColor: Colors.black12,
        elevation: 0,
        fixedColor: Colors.deepOrangeAccent[100], // 选中颜色
        type: BottomNavigationBarType.fixed,  // 超过三个底部导航项时要设置类型，
        onTap: (int index){
          setState(() {
            _currentIndex = index;
          });
        },
        currentIndex: _currentIndex,  // 当前选中索引
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home_sharp), label: '主页'),
          BottomNavigationBarItem(icon: Icon(Icons.games), label: '游戏'),
          BottomNavigationBarItem(icon: Icon(Icons.shop), label: '商城'),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: '我的'),
        ],
      ),
    );
  }
}

